<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>营养仪表盘 - 智能营养管理系统</title>
    <style>
        /* 基本样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        .navbar {
            background-color: #007bff;
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }
        
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
            text-decoration: none;
        }
        
        .page-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 2rem 0;
            border-radius: 10px;
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .row {
            display: flex;
            flex-wrap: wrap;
            margin: -15px;
        }
        
        .col-md-3 {
            flex: 0 0 25%;
            max-width: 25%;
            padding: 15px;
        }
        
        .col-md-6 {
            flex: 0 0 50%;
            max-width: 50%;
            padding: 15px;
        }
        
        .col-md-12 {
            flex: 0 0 100%;
            max-width: 100%;
            padding: 15px;
        }
        
        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 1.5rem;
            margin-bottom: 1rem;
            height: 100%;
        }
        
        .card-header {
            border-bottom: 1px solid #dee2e6;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }
        
        .card-title {
            font-size: 1.25rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
        }
        
        .alert-warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .alert-info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        
        .progress {
            background-color: #e9ecef;
            border-radius: 0.25rem;
            height: 1rem;
            overflow: hidden;
            margin-bottom: 0.5rem;
        }
        
        .progress-bar {
            background-color: #007bff;
            height: 100%;
            transition: width 0.6s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.75rem;
        }
        
        .progress-bar-success {
            background-color: #28a745;
        }
        
        .progress-bar-warning {
            background-color: #ffc107;
        }
        
        .progress-bar-danger {
            background-color: #dc3545;
        }
        
        .nutrition-item {
            margin-bottom: 1.5rem;
        }
        
        .nutrition-label {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        .nutrition-value {
            font-size: 1.1rem;
            font-weight: bold;
        }
        
        .nutrition-target {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .btn {
            display: inline-block;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #0056b3;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .text-center {
            text-align: center;
        }
        
        .text-muted {
            color: #6c757d;
        }
        
        .mb-3 {
            margin-bottom: 1rem;
        }
        
        .date-selector {
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .date-selector input {
            padding: 0.5rem;
            border: 1px solid #ced4da;
            border-radius: 5px;
            font-size: 1rem;
        }
        
        .badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 0.25rem;
            margin-left: 0.5rem;
        }
        
        .badge-primary {
            background-color: #007bff;
            color: white;
        }
        
        .badge-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        @media (max-width: 768px) {
            .col-md-3, .col-md-6, .col-md-12 {
                flex: 0 0 100%;
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="container">
            <a class="navbar-brand" href="/">🍃 智能营养管理系统</a>
        </div>
    </nav>
    
    <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1>📊 营养仪表盘</h1>
            <p>追踪您的每日营养摄入情况</p>
        </div>
        
        <!-- 日期选择器 -->
        <div class="date-selector">
            <input type="date" id="dateSelector" th:value="${targetDate}" onchange="changeDate()">
            <span class="badge badge-primary" th:if="${isToday}">今日</span>
            <span class="badge badge-secondary" th:unless="${isToday}">历史</span>
        </div>
        
        <!-- 营养预警 -->
        <div class="alert alert-warning">
            <h5>⚠️ 营养预警</h5>
            <div>
                <strong>卡路里摄入不足</strong>
            </div>
            <div>
                <span>蛋白质摄入偏低</span>
            </div>
        </div>
        
        <!-- 营养指标 -->
        <div class="row">
            <!-- 卡路里 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🔥 卡路里</h5>
                    </div>
                    <div class="nutrition-item">
                        <div class="nutrition-label">
                            <span class="nutrition-value" id="caloriesValue">0 / 2000 kcal</span>
                            <span class="nutrition-target" id="caloriesPercent">0.0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="caloriesBar" style="width: 0%">
                            </div>
                        </div>
                        <small class="text-muted" id="caloriesGoalText">目标: 2000 kcal</small>
                    </div>
                </div>
            </div>
            
            <!-- 蛋白质 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🥩 蛋白质</h5>
                    </div>
                    <div class="nutrition-item">
                        <div class="nutrition-label">
                            <span class="nutrition-value" id="proteinValue">0.0 / 150.0 g</span>
                            <span class="nutrition-target" id="proteinPercent">0.0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="proteinBar" style="width: 0%">
                            </div>
                        </div>
                        <small class="text-muted" id="proteinGoalText">目标: 150.0 g</small>
                    </div>
                </div>
            </div>
            
            <!-- 碳水化合物 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🍞 碳水化合物</h5>
                    </div>
                    <div class="nutrition-item">
                        <div class="nutrition-label">
                            <span class="nutrition-value" id="carbsValue">0.0 / 250.0 g</span>
                            <span class="nutrition-target" id="carbsPercent">0.0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="carbsBar" style="width: 0%">
                            </div>
                        </div>
                        <small class="text-muted" id="carbsGoalText">目标: 250.0 g</small>
                    </div>
                </div>
            </div>
            
            <!-- 脂肪 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🥑 脂肪</h5>
                    </div>
                    <div class="nutrition-item">
                        <div class="nutrition-label">
                            <span class="nutrition-value" id="fatValue">0.0 / 65.0 g</span>
                            <span class="nutrition-target" id="fatPercent">0.0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="fatBar" style="width: 0%">
                            </div>
                        </div>
                        <small class="text-muted" id="fatGoalText">目标: 65.0 g</small>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 今日点餐记录 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🍽️ 今日点餐记录</h5>
                    </div>
                    <div id="ordersSection" class="text-center text-muted">
                        <p id="ordersEmpty">今日尚未��录任何营养摄入，请及时用餐并记录。</p>
                        <div id="ordersList" style="display:none; text-align:left; padding: 0 1rem;">
                            <!-- 动态填充订单条目 -->
                        </div>
                        <div style="margin-top: 1rem;">
                            <a href="/meals" class="btn btn-primary">去点餐</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        function changeDate() {
            const date = document.getElementById('dateSelector').value;
            window.location.href = '/nutrition/dashboard?date=' + date;
        }

        // 页面加载后拉取营养数据并更新
        document.addEventListener('DOMContentLoaded', function() {
            loadNutritionData();
            loadTodayOrders();
            // 每60秒自动刷新一次，点餐后返回本页可自动更新
            setInterval(() => { loadNutritionData(); loadTodayOrders(); }, 60000);
        });

        function loadNutritionData() {
            fetch('/nutrition/api/progress')
                .then(resp => {
                    if (!resp.ok) throw new Error('HTTP ' + resp.status);
                    return resp.json();
                })
                .then(data => {
                    console.debug('营养数据API返回:', data);
                    updateDisplay(data);
                })
                .catch(err => {
                    console.error('加载营养数据失败:', err);
                    updateDisplay({}); // 使用默认
                });
        }

        function loadTodayOrders() {
            fetch('/nutrition/api/today-orders')
                .then(resp => {
                    if (!resp.ok) throw new Error('HTTP ' + resp.status);
                    return resp.json();
                })
                .then(list => {
                    const emptyEl = document.getElementById('ordersEmpty');
                    const listEl = document.getElementById('ordersList');
                    if (!Array.isArray(list) || list.length === 0) {
                        if (emptyEl) emptyEl.style.display = '';
                        if (listEl) { listEl.style.display = 'none'; listEl.innerHTML = ''; }
                        return;
                    }
                    // 渲染列表
                    const groups = { BREAKFAST: [], LUNCH: [], DINNER: [], SNACK: [] };
                    list.forEach(o => { (groups[o.mealType] ||= []).push(o); });
                    const mealName = { BREAKFAST: '早餐', LUNCH: '午餐', DINNER: '晚餐', SNACK: '小食' };
                    let html = '';
                    Object.keys(groups).forEach(k => {
                        const arr = groups[k];
                        if (arr && arr.length) {
                            html += `<div style="margin: .5rem 0; font-weight: 600;">${mealName[k]}</div>`;
                            arr.forEach(o => {
                                const kcal = Number(o.actualCalories || 0).toFixed(0);
                                const portion = o.portionSize || 1;
                                html += `<div style="padding: .25rem 0; display:flex; justify-content:space-between; border-bottom:1px dashed #eee;">
                                    <span>${o.dishName} × ${portion}</span>
                                    <span style="color:#6c757d;">${kcal} kcal</span>
                                </div>`;
                            });
                        }
                    });
                    if (emptyEl) emptyEl.style.display = 'none';
                    if (listEl) { listEl.style.display = ''; listEl.innerHTML = html; }
                })
                .catch(err => {
                    console.error('加载今日点餐记录失败:', err);
                });
        }

        function clampPercent(n) { return Math.max(0, Math.min(100, n)); }

        function updateMetric(prefix, total, goal, unit, roundTo) {
            const percent = goal > 0 ? (total / goal * 100) : 0;
            const pctText = `${percent.toFixed(1)}%`;
            const barWidth = `${clampPercent(percent)}%`;

            const totalText = roundTo === 0 ? Math.round(total).toString() : total.toFixed(roundTo);
            const goalText = roundTo === 0 ? Math.round(goal).toString() : goal.toFixed(roundTo);

            const valueEl = document.getElementById(prefix + 'Value');
            const percentEl = document.getElementById(prefix + 'Percent');
            const barEl = document.getElementById(prefix + 'Bar');
            const goalEl = document.getElementById(prefix + 'GoalText');

            if (valueEl) valueEl.textContent = `${totalText} / ${goalText} ${unit}`;
            if (percentEl) percentEl.textContent = pctText;
            if (barEl) barEl.style.width = barWidth;
            if (goalEl) goalEl.textContent = `目标: ${goalText} ${unit}`;
        }

        function updateDisplay(data) {
            // 兼容两种字段命名
            const calories = Number(data.totalCalories ?? data.calories ?? 0);
            const caloriesGoal = Number(data.targetCalories ?? data.caloriesGoal ?? 2000);
            const protein = Number(data.totalProtein ?? data.protein ?? 0);
            const proteinGoal = Number(data.targetProtein ?? data.proteinGoal ?? 150);
            const carbs = Number(data.totalCarbs ?? data.carbs ?? 0);
            const carbsGoal = Number(data.targetCarbs ?? data.carbsGoal ?? 250);
            const fat = Number(data.totalFat ?? data.fat ?? 0);
            const fatGoal = Number(data.targetFat ?? data.fatGoal ?? 65);

            updateMetric('calories', calories, caloriesGoal, 'kcal', 0);
            updateMetric('protein', protein, proteinGoal, 'g', 1);
            updateMetric('carbs', carbs, carbsGoal, 'g', 1);
            updateMetric('fat', fat, fatGoal, 'g', 1);
        }
    </script>
</body>
</html>
